#include "CGame.h"
#include "CEntity.h"
#include "CPlayer.h"
#include "CAIModule_ChasePlayer.h"

#include <iostream>

CAIModule_ChasePlayer::CAIModule_ChasePlayer(CEntity* host) : CAIModule(host)
{
	PlayerPosition = gPlayer->getPosition();
	Path.create(gGame->getDungeon()->getFloor(host->getCurrentFloor())->getFovMap(), host->getPosition(), PlayerPosition);
}

int CAIModule_ChasePlayer::action()
{
	int delay = Host->getSpeed();
	if (Host->canSeePlayer())
	{
		PlayerPosition = gPlayer->getPosition();
		Path.change(Host->getPosition(), PlayerPosition);

		int x = Host->getPosition().x(), y = Host->getPosition().y();
		Path.move(&x, &y);

		if (Path.getDestination() != pair(x, y))
		{
			for (unsigned int i = 0; i < gGame->getDungeon()->getFloor(Host->getCurrentFloor())->getTile(pair(Host->getPosition().x(), Host->getPosition().y()))->entities.size(); ++i)
				if (gGame->getDungeon()->getFloor(Host->getCurrentFloor())->getTile(pair(Host->getPosition().x(), Host->getPosition().y()))->entities[i] == Host)
					gGame->getDungeon()->getFloor(Host->getCurrentFloor())->getTile(pair(Host->getPosition().x(), Host->getPosition().y()))->entities.erase(gGame->getDungeon()->getFloor(Host->getCurrentFloor())->getTile(pair(Host->getPosition().x(), Host->getPosition().y()))->entities.begin()+i);

			Host->setPosition(pair(x, y));

			gGame->getDungeon()->getFloor(Host->getCurrentFloor())->getTile(pair(x, y))->entities.push_back(Host);
		}
		else if (!gPlayer->isDead())
			delay = Host->attack(gPlayer);
	}

	return delay;
}
